package com.example.base.aop.permission

import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.SystemClock
import android.provider.Settings
import androidx.fragment.app.Fragment
import androidx.fragment.app.commit
import com.example.base.R
import com.example.base.ext.confirmDialog

/**  代理请求权限的 Fragment  **/
class RequestPermissionFragment : Fragment() {

    /**  权限请求回调接口  **/
    var requestPermissionCallback: RequestPermissionCallback? = null

    /**  待请求的权限列表  **/
    var permissions: Array<out String> = emptyArray()

    /**  上次请求权限的时间  **/
    private var lastRequestTime: Long = 0

    /**  重置请求时间  **/
    fun resetRequestTime() {
        lastRequestTime = SystemClock.elapsedRealtime()
    }

    private val permissionTool: PermissionTool by lazy {
        PermissionTool.getInstance(requireActivity()).request(permissions)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        if (requestCode != PermissionTool.REQUEST_PERMISSION_CODE) return

        var isOk = true

        // 检查用户是否授权全部权限
        for (grantResult in grantResults) {
            if (grantResult == PackageManager.PERMISSION_DENIED) {
                isOk = false
                break
            }
        }

        if (isOk) {
            detachSelf()
            requestPermissionCallback?.onSuccess()
        } else {
            // 如果距离上次请求时间小于 300 毫秒, 则表示用户已勾选了永远拒绝权限, 需要引导用户去设置界面进行手动授权
            if (SystemClock.elapsedRealtime() - lastRequestTime < 300) showHintDialog()
            // 否则则为档次请求被拒绝, 返回被拒绝的权限即可
            else requestPermissionCallback?.onError(permissions)
        }
    }

    /**  显示提示弹窗, 引导用户去设置界面进行手动授权  **/
    fun showHintDialog() {
        val buffer = StringBuffer()
        val notGrantedPermissions = permissionTool.getUserNotGrantedPermissions()
        notGrantedPermissions.forEach { notGrantedPermission ->
            val permissionName = permissionTool.getPermissionName(notGrantedPermission)
            if (permissionName.isNotEmpty())
                buffer.append(" [").append(permissionName).append("] ")
        }

        // 弹窗引导
        requireActivity().confirmDialog(
            getString(R.string.system_dialog_title),
            getString(R.string.need_permission_hint, buffer.toString()),
            getString(R.string.dialog_agree_text),
            getString(R.string.dialog_deny_text)
        ) { dialog, isConfirm ->
            if (isConfirm) navigationToSettingActivity()
            else requestPermissionCallback?.onError(permissions)
            dialog.dismiss()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode != PermissionTool.REQUEST_PERMISSION_CODE) return

        // 检验 用户从设置界面回来后是否还存在未授权的权限
        val notGrantedPermissions = permissionTool.getUserNotGrantedPermissions()
        if (notGrantedPermissions.isEmpty()) requestPermissionCallback?.onSuccess()
        else requestPermissionCallback?.onError(notGrantedPermissions)
        detachSelf()
    }

    /**  将自己与 Activity 进行解绑  **/
    private fun detachSelf() {
        if (!isAdded) return
        fragmentManager?.commit {
            this.detach(this@RequestPermissionFragment)
            this.remove(this@RequestPermissionFragment)
        }
    }

    /**  跳转到当前 App 的系统详细设置界面  **/
    private fun navigationToSettingActivity() {
        val intent = Intent().apply {
            action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
            data = Uri.fromParts("package", requireActivity().packageName, null)
        }
        startActivityForResult(intent, PermissionTool.REQUEST_PERMISSION_CODE)
    }

}